/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

// 等待设备就绪
document.addEventListener('deviceready', function() {
    console.log('设备就绪，网络状态监听功能可用');
    // 延迟初始化，确保网络插件已完全加载
    setTimeout(function() {
        initNetworkMonitor();
    }, 300);
}, false);

// 网络类型映射
const networkTypeMap = {
    'unknown': { name: '未知网络', icon: '❓', color: 'unknown', badge: 'badge-unknown' },
    'ethernet': { name: '以太网', icon: '🔌', color: 'wifi', badge: 'badge-wifi' },
    'wifi': { name: 'WiFi', icon: '📶', color: 'wifi', badge: 'badge-wifi' },
    '2g': { name: '2G', icon: '📱', color: 'cellular', badge: 'badge-cellular' },
    '3g': { name: '3G', icon: '📱', color: 'cellular', badge: 'badge-cellular' },
    '4g': { name: '4G', icon: '📱', color: 'cellular', badge: 'badge-cellular' },
    'cellular': { name: '蜂窝网络', icon: '📱', color: 'cellular', badge: 'badge-cellular' },
    'none': { name: '离线', icon: '❌', color: 'offline', badge: 'badge-offline' }
};

// 初始化网络状态监听
function initNetworkMonitor() {
    // 检查 navigator.connection 是否可用
    if (typeof navigator.connection === 'undefined') {
        console.warn('navigator.connection 不可用，使用基础网络检测');
        updateNetworkStatusBasic();
        return;
    }

    // 添加网络类型常量（如果插件没有自动添加）
    if (!navigator.connection.UNKNOWN) {
        navigator.connection.UNKNOWN = 'unknown';
        navigator.connection.ETHERNET = 'ethernet';
        navigator.connection.WIFI = 'wifi';
        navigator.connection.CELL_2G = '2g';
        navigator.connection.CELL_3G = '3g';
        navigator.connection.CELL_4G = '4g';
        navigator.connection.CELLULAR = 'cellular';
        navigator.connection.NONE = 'none';
    }

    // 等待连接信息准备好后再获取状态
    // 使用 getInfo() 方法主动获取网络状态，确保获取到最新状态
    let retryCount = 0;
    const maxRetries = 3;
    
    function tryGetNetworkInfo() {
        if (typeof navigator.connection.getInfo === 'function') {
            // 主动获取网络状态
            navigator.connection.getInfo(
                function(networkType) {
                    console.log('获取到网络类型：', networkType);
                    retryCount = 0; // 成功后重置计数
                    // 更新 connection.type
                    if (navigator.connection) {
                        navigator.connection.type = networkType;
                    }
                    // 更新显示
                    updateNetworkStatus();
                },
                function(error) {
                    console.warn('获取网络状态失败：', error);
                    retryCount++;
                    // 如果获取失败，重试（最多3次）
                    if (retryCount < maxRetries) {
                        console.log(`重试获取网络状态 (${retryCount}/${maxRetries})...`);
                        setTimeout(tryGetNetworkInfo, 500);
                    } else {
                        console.warn('获取网络状态失败，已达到最大重试次数，使用 type 属性');
                        // 如果重试失败，尝试使用 type 属性
                        setTimeout(function() {
                            updateNetworkStatus();
                        }, 200);
                    }
                }
            );
        } else {
            // 如果没有 getInfo 方法，延迟一下再获取（等待插件初始化）
            retryCount++;
            if (retryCount < maxRetries) {
                console.log(`等待插件初始化 (${retryCount}/${maxRetries})...`);
                setTimeout(tryGetNetworkInfo, 500);
            } else {
                console.log('使用 type 属性获取网络状态');
                updateNetworkStatus();
            }
        }
    }
    
    // 开始尝试获取网络信息
    tryGetNetworkInfo();

    // 监听在线事件
    document.addEventListener('online', function() {
        console.log('网络已连接');
        addEventLog('网络已连接', 'online');
        // 延迟更新，确保状态已同步
        setTimeout(function() {
            updateNetworkStatus();
        }, 100);
    }, false);

    // 监听离线事件
    document.addEventListener('offline', function() {
        console.log('网络已断开');
        addEventLog('网络已断开', 'offline');
        // 延迟更新，确保状态已同步
        setTimeout(function() {
            updateNetworkStatus();
        }, 100);
    }, false);

    // 监听网络类型变化事件（如果支持）
    if (typeof document.addEventListener !== 'undefined') {
        document.addEventListener('networkconnectionchange', function() {
            console.log('网络类型已变化');
            addEventLog('网络类型已变化', 'change');
            // 重新获取网络状态
            if (typeof navigator.connection.getInfo === 'function') {
                navigator.connection.getInfo(
                    function(networkType) {
                        console.log('网络类型变化为：', networkType);
                        if (navigator.connection) {
                            navigator.connection.type = networkType;
                        }
                        updateNetworkStatus();
                    },
                    function(error) {
                        console.warn('获取网络状态失败：', error);
                        updateNetworkStatus();
                    }
                );
            } else {
                updateNetworkStatus();
            }
        }, false);
    }
}

// 更新网络状态显示
function updateNetworkStatus() {
    const statusIcon = document.getElementById('status-icon');
    const statusText = document.getElementById('status-text');
    const statusDetails = document.getElementById('status-details');

    // 获取网络类型（按照示例代码的方式）
    let networkType = 'unknown';
    let isOnline = true;
    
    if (typeof navigator.connection !== 'undefined' && navigator.connection.type) {
        networkType = navigator.connection.type;
        
        // 根据网络类型判断是否在线
        // 使用常量进行比较（如果可用）
        const NONE = navigator.connection.NONE || 'none';
        if (networkType === NONE) {
            isOnline = false;
        } else {
            // 只要不是 'none'，就认为在线
            isOnline = true;
        }
    } else if (typeof navigator.onLine !== 'undefined') {
        // 如果没有 connection.type，使用 onLine
        isOnline = navigator.onLine;
        networkType = isOnline ? 'unknown' : 'none';
    }
    
    console.log('当前网络状态 - type:', networkType, 'isOnline:', isOnline);

    // 获取网络信息（使用常量进行比较，如示例代码）
    let networkInfo = networkTypeMap[networkType] || networkTypeMap['unknown'];
    
    // 如果可以使用常量，使用常量进行比较（如示例代码）
    if (typeof navigator.connection !== 'undefined') {
        const WIFI = navigator.connection.WIFI || 'wifi';
        const NONE = navigator.connection.NONE || 'none';
        const CELL_2G = navigator.connection.CELL_2G || '2g';
        const CELL_3G = navigator.connection.CELL_3G || '3g';
        const CELL_4G = navigator.connection.CELL_4G || '4g';
        const CELLULAR = navigator.connection.CELLULAR || 'cellular';
        
        // 根据网络类型设置显示（按照示例代码的逻辑）
        if (networkType === WIFI) {
            networkInfo = networkTypeMap['wifi'];
        } else if (networkType === CELL_2G || networkType === CELL_3G || networkType === CELL_4G || networkType === CELLULAR) {
            networkInfo = networkTypeMap[networkType] || networkTypeMap['cellular'];
        } else if (networkType === NONE) {
            networkInfo = networkTypeMap['none'];
        }
    }
    
    // 更新图标和文本
    statusIcon.textContent = networkInfo.icon;
    statusText.textContent = `当前网络：${networkInfo.name}`;
    statusText.className = `status-text ${networkInfo.color}`;

    // 更新详细信息
    let detailsHTML = '';
    
    // 网络类型
    detailsHTML += `
        <div class="detail-item">
            <span class="detail-label">网络类型</span>
            <span class="detail-value">
                <span class="network-type-badge ${networkInfo.badge}">${networkType.toUpperCase()}</span>
            </span>
        </div>
    `;

    // 在线状态（使用上面计算的值）
    detailsHTML += `
        <div class="detail-item">
            <span class="detail-label">在线状态</span>
            <span class="detail-value" style="color: ${isOnline ? '#27ae60' : '#e74c3c'};">
                ${isOnline ? '✅ 在线' : '❌ 离线'}
            </span>
        </div>
    `;
    
    // 调试信息
    if (typeof navigator.connection !== 'undefined') {
        detailsHTML += `
            <div class="detail-item">
                <span class="detail-label">connection.type</span>
                <span class="detail-value" style="font-size: 12px; color: #95a5a6;">
                    ${navigator.connection.type || 'undefined'}
                </span>
            </div>
            <div class="detail-item">
                <span class="detail-label">navigator.onLine</span>
                <span class="detail-value" style="font-size: 12px; color: #95a5a6;">
                    ${typeof navigator.onLine !== 'undefined' ? navigator.onLine : 'undefined'}
                </span>
            </div>
        `;
    }

    // 如果 navigator.connection 可用，显示更多信息
    if (typeof navigator.connection !== 'undefined') {
        // 显示网络类型常量（用于调试）
        if (navigator.connection.WIFI) {
            detailsHTML += `
                <div class="detail-item">
                    <span class="detail-label">网络常量</span>
                    <span class="detail-value" style="font-size: 12px; color: #95a5a6;">
                        WIFI: ${navigator.connection.WIFI}, NONE: ${navigator.connection.NONE || 'undefined'}
                    </span>
                </div>
            `;
        }

        // 是否支持高精度网络检测
        if (navigator.connection.downlinkMax !== undefined) {
            detailsHTML += `
                <div class="detail-item">
                    <span class="detail-label">最大下行速度</span>
                    <span class="detail-value">${navigator.connection.downlinkMax} Mbps</span>
                </div>
            `;
        }
    }

    // 当前时间
    const currentTime = new Date().toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
    });
    detailsHTML += `
        <div class="detail-item">
            <span class="detail-label">更新时间</span>
            <span class="detail-value">${currentTime}</span>
        </div>
    `;

    statusDetails.innerHTML = detailsHTML;

    // 添加状态更新日志
    addEventLog(`网络状态更新：${networkInfo.name}`, 'change');
}

// 基础网络状态检测（当 navigator.connection 不可用时）
function updateNetworkStatusBasic() {
    const statusIcon = document.getElementById('status-icon');
    const statusText = document.getElementById('status-text');
    const statusDetails = document.getElementById('status-details');

    const isOnline = navigator.onLine !== undefined ? navigator.onLine : true;
    
    if (isOnline) {
        statusIcon.textContent = '📶';
        statusText.textContent = '当前网络：在线';
        statusText.className = 'status-text wifi';
    } else {
        statusIcon.textContent = '❌';
        statusText.textContent = '当前网络：离线';
        statusText.className = 'status-text offline';
    }

    const currentTime = new Date().toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
    });

    statusDetails.innerHTML = `
        <div class="detail-item">
            <span class="detail-label">在线状态</span>
            <span class="detail-value" style="color: ${isOnline ? '#27ae60' : '#e74c3c'};">
                ${isOnline ? '✅ 在线' : '❌ 离线'}
            </span>
        </div>
        <div class="detail-item">
            <span class="detail-label">更新时间</span>
            <span class="detail-value">${currentTime}</span>
        </div>
        <div class="detail-item">
            <span class="detail-label">提示</span>
            <span class="detail-value" style="color: #95a5a6; font-size: 12px;">
                网络类型检测需要 Cordova Network Information 插件支持
            </span>
        </div>
    `;

    // 监听在线/离线事件
    document.addEventListener('online', function() {
        addEventLog('网络已连接', 'online');
        updateNetworkStatusBasic();
    }, false);

    document.addEventListener('offline', function() {
        addEventLog('网络已断开', 'offline');
        updateNetworkStatusBasic();
    }, false);
}

// 添加事件日志
function addEventLog(message, type = 'info') {
    const eventLogContent = document.getElementById('event-log-content');
    if (!eventLogContent) return;

    const eventItem = document.createElement('div');
    eventItem.className = `event-item ${type}`;
    
    const currentTime = new Date().toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
    });
    
    eventItem.innerHTML = `
        <span>${message}</span>
        <span class="event-time">${currentTime}</span>
    `;

    // 插入到最前面
    eventLogContent.insertBefore(eventItem, eventLogContent.firstChild);

    // 限制日志数量（最多保留50条）
    while (eventLogContent.children.length > 50) {
        eventLogContent.removeChild(eventLogContent.lastChild);
    }
}

// 页面加载完成后的初始化
document.addEventListener('DOMContentLoaded', function() {
    console.log('网络状态监听页面加载完成');
    
    // 如果不在 Cordova 环境中，使用基础检测
    if (typeof cordova === 'undefined') {
        console.log('检测到浏览器环境，使用基础网络检测');
        updateNetworkStatusBasic();
        
        // 监听在线/离线事件
        window.addEventListener('online', function() {
            addEventLog('网络已连接', 'online');
            updateNetworkStatusBasic();
        });
        
        window.addEventListener('offline', function() {
            addEventLog('网络已断开', 'offline');
            updateNetworkStatusBasic();
        });
    }
});

